<template>
  <div class="news-container">
    <el-card class="news-card">
      <template #header>
        <div class="news-header">
          <h1>新闻管理</h1>
          <el-form :inline="true" class="news-filter" @submit.prevent="searchNews">
            <el-form-item label="新闻标题">
              <el-input v-model="searchForm.newsTitle" placeholder="请输入新闻标题" clearable />
            </el-form-item>
            <el-form-item label="作者">
              <el-input v-model="searchForm.author" placeholder="请输入作者" clearable />
            </el-form-item>
            <el-form-item label="新闻简介">
              <el-input v-model="searchForm.newsSummary" placeholder="请输入新闻简介" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchNews" :loading="loading">查询</el-button>
              <el-button type="success" @click="showAddModal" :loading="loading">新增新闻</el-button>
              <el-button type="info" @click="exportToExcel" :loading="loading">导出Excel</el-button>
              <el-button type="danger" @click="batchDelete" :loading="loading" :disabled="selectedNews.length === 0">
                批量删除
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <el-table :data="newsList" @selection-change="handleSelectionChange" v-loading="loading">
        <el-table-column type="selection" width="55" :selectable="isSelectable" />
        <el-table-column prop="newsTitle" label="新闻标题" min-width="200" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="newsSummary" label="新闻简介" min-width="200" show-overflow-tooltip />
        <!-- 审核状态列 - 所有用户可见 -->
        <el-table-column label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="getReviewStatusType(scope.row.newsStatus)">
              {{ getReviewStatusText(scope.row.newsStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" type="info" @click="viewDetail(scope.row)">查看详情</el-button>
              <!-- 编辑按钮 - 只有管理员或新闻创建者可以编辑 -->
              <el-button v-if="isAdmin || scope.row.creatPersonId === currentUserId" size="small" type="warning"
                @click="editNews(scope.row)">
                编辑
              </el-button>

              <!-- 审核操作下拉菜单 - 只有管理员可见，且只对未审核的新闻显示 -->
              <el-dropdown v-if="isAdmin && scope.row.newsStatus === 0" @command="handleReviewCommand">
                <el-button size="small" type="success">
                  审核操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ action: 'approve', newsId: scope.row.newsId }">
                      <el-icon>
                        <check />
                      </el-icon>审核通过
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'reject', newsId: scope.row.newsId }">
                      <el-icon>
                        <close />
                      </el-icon>审核拒绝
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <!-- 删除按钮 - 只有管理员或新闻创建者可以删除 -->
              <el-button v-if="isAdmin || scope.row.creatPersonId === currentUserId" size="small" type="danger"
                @click="deleteNewsItem(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination v-model:current-page="currentPage" :page-size="10" :total="total"
          layout="total, prev, pager, next, jumper" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="showModal" :title="isEdit ? '编辑新闻' : '新增新闻'" width="800px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="新闻标题" prop="newsTitle">
          <el-input v-model="formData.newsTitle" placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="formData.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="新闻简介" prop="newsSummary">
          <el-input v-model="formData.newsSummary" placeholder="请输入新闻简介" />
        </el-form-item>
        <el-form-item label="图片路径" prop="newsImagePath">
          <div class="image-upload-container">
            <el-input v-model="formData.newsImagePath" placeholder="请输入图片名称或选择图片" readonly class="image-input" />
            <el-button type="primary" @click="selectImage" class="select-image-btn">
              选择图片
            </el-button>
            <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleImageSelect" />
          </div>
          <div class="form-tip">支持 jpg、png、gif 等图片格式</div>
          <div v-if="formData.newsImagePath" class="image-preview">
            <img :src="getImageUrl(formData.newsImagePath)" :alt="formData.newsImagePath" @error="handleImageError" />
            <span class="image-name">{{ formData.newsImagePath }}</span>
          </div>
        </el-form-item>
        <div class="form-group">
          <label>新闻内容 *</label>
          <div class="editor-container">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 300px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="handleCreated" />
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeModal">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="showDetailModal" title="新闻详情" width="800px">
      <div v-if="currentNews" class="news-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="新闻ID">{{ currentNews.newsId }}</el-descriptions-item>
          <el-descriptions-item label="新闻标题">{{ currentNews.newsTitle }}</el-descriptions-item>
          <el-descriptions-item label="作者">{{ currentNews.author }}</el-descriptions-item>
          <el-descriptions-item label="创建人ID">{{ currentNews.creatPersonId }}</el-descriptions-item>
          <!-- 审核状态 - 所有用户可见 -->
          <el-descriptions-item label="审核状态">
            <el-tag :type="getReviewStatusType(currentNews.newsStatus)">
              {{ getReviewStatusText(currentNews.newsStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="新闻简介" :span="2">{{ currentNews.newsSummary }}</el-descriptions-item>
          <el-descriptions-item label="图片" :span="2">
            <el-image v-if="currentNews.newsImagePath" :src="getImageUrl(currentNews.newsImagePath)"
              :alt="currentNews.newsTitle" style="max-width: 200px; max-height: 150px" fit="cover"
              :preview-src-list="[getImageUrl(currentNews.newsImagePath)]">
              <template #error>
                <div class="image-error">加载失败</div>
              </template>
            </el-image>
            <span v-else>无图片</span>
          </el-descriptions-item>
          <el-descriptions-item label="新闻内容" :span="2">
            <div class="news-content" v-html="currentNews.newsContent"></div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, shallowRef, onBeforeUnmount, onBeforeMount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Check, Close } from '@element-plus/icons-vue'
import NewsService from '../services/NewsService'
import UserService from '../services/UserService.js'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 响应式数据
const newsList = ref([])
const selectedNews = ref([])
const loading = ref(false)
const showModal = ref(false)
const showDetailModal = ref(false)
const isEdit = ref(false)
const currentNews = ref(null)
const formRef = ref()
const fileInput = ref(null)


// 当前用户信息 - 使用UserService
const currentUserId = computed(() => UserService.getCurrentUserId())
const isAdmin = computed(() => UserService.isAdmin())


const isSelectable = computed(() => {
  return (row) => {
    // 如果是管理员，所有行都可选
    const currentUserStr = localStorage.getItem('currentUser');

    if (JSON.parse(currentUserStr).userType === 2) return true

    // 否则，只有自己创建的资讯可选
    return row.creatPersonId === currentUserId.value
  }
})

// 分页相关数据
const currentPage = ref(1)
const total = ref(0)

// 富文本编辑器相关
const editorRef = shallowRef()
const valueHtml = ref('<p>请输入新闻内容...</p>')
const mode = ref('default')
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入新闻内容...',
  MENU_CONF: {}
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor
}

const searchForm = reactive({
  newsTitle: '',
  author: '',
  newsSummary: '',
  newsImagePath: ''
})

const formData = reactive({
  newsId: null,
  newsTitle: '',
  author: '',
  newsSummary: '',
  newsImagePath: '',
  newsContent: '',
  creatPersonId: 1
})

// 表单验证规则
const rules = {
  newsTitle: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  newsSummary: [
    { required: true, message: '请输入新闻简介', trigger: 'blur' }
  ]
}

// 计算属性
const isAllSelected = computed(() => {
  return newsList.value.length > 0 && selectedNews.value.length === newsList.value.length
})

// 方法
const loadNewsList = async () => {
  loading.value = true
  try {
    // 构建查询参数，包含分页信息
    const params = {
      current: currentPage.value
    };

    const response = await NewsService.getNewsListWithPage(params)
    console.log('response:', response)
    if (response.code === 200) {
      const pageData = response.data;
      newsList.value = pageData.records || [];
      total.value = pageData.total || 0;

      // 确保审核状态字段存在
      newsList.value.forEach(news => {
        if (news.newsStatus === undefined || news.newsStatus === null) {
          news.newsStatus = 0;
        }
      });
      console.log('newsList:', newsList.value)
    } else {
      ElMessage.error(response.message || '获取新闻列表失败')
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  } finally {
    loading.value = false
  }
}

const searchNews = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value
    };

    Object.keys(searchForm).forEach(key => {
      if (searchForm[key]) {
        params[key] = searchForm[key]
      }
    })
    console.log('params:', params)

    const response = await NewsService.getNewsListWithPage(params)
    if (response.code === 200) {
      const pageData = response.data;
      newsList.value = pageData.records || [];
      total.value = pageData.total || 0;

      // 确保审核状态字段存在
      newsList.value.forEach(news => {
        if (news.newsStatus === undefined || news.newsStatus === null) {
          news.newsStatus = 0;
        }
      });
    } else {
      ElMessage.error(response.message || '搜索新闻失败')
    }
  } catch (error) {
    console.error('搜索新闻失败:', error)
    ElMessage.error('搜索新闻失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1; // 重置到第一页
  loadNewsList()
}

const showAddModal = () => {
  isEdit.value = false
  Object.keys(formData).forEach(key => {
    if (key === 'creatPersonId') {
      formData[key] = currentUserId.value; // 使用当前用户ID
    } else {
      formData[key] = ''
    }
  })
  formData.newsId = null
  valueHtml.value = '<p>请输入新闻内容...</p>'
  showModal.value = true
}

const editNews = (news) => {
  // 权限验证：只有管理员或新闻创建者可以编辑
  if (!isAdmin.value && news.creatPersonId !== currentUserId.value) {
    ElMessage.warning('您没有权限修改此新闻');
    return;
  }

  isEdit.value = true
  Object.keys(formData).forEach(key => {
    formData[key] = news[key] || ''
  })
  valueHtml.value = news.newsContent || '<p>请输入新闻内容...</p>'
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
  formRef.value?.resetFields()
  valueHtml.value = '<p>请输入新闻内容...</p>'
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证富文本内容
    if (!valueHtml.value || valueHtml.value === '<p>请输入新闻内容...</p>' || valueHtml.value.trim() === '') {
      ElMessage.warning('请输入新闻内容')
      return
    }

    // 将富文本内容同步到formData
    formData.newsContent = valueHtml.value

    let response
    if (isEdit.value) {
      response = await NewsService.updateNews(formData)
    } else {
      response = await NewsService.addNews(formData)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      closeModal()
      loadNewsList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

const viewDetail = async (news) => {
  try {
    const response = await NewsService.getNewsDetail(news.newsId)
    if (response.code === 200) {
      currentNews.value = response.data
    } else {
      console.error('获取详情失败:', response.message)
      currentNews.value = news
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    currentNews.value = news
  }
  showDetailModal.value = true
}

const deleteNewsItem = async (news) => {
  // 权限验证：只有管理员或新闻创建者可以删除
  if (!isAdmin.value && news.creatPersonId !== currentUserId.value) {
    ElMessage.warning('您没有权限删除此新闻');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除新闻"${news.newsTitle}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await NewsService.deleteNews(news.newsId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadNewsList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

const batchDelete = async () => {
  if (selectedNews.value.length === 0) {
    ElMessage.warning('请选择要删除的新闻')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedNews.value.length} 条新闻吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await NewsService.batchDeleteNews(selectedNews.value)
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      selectedNews.value = []
      loadNewsList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请重试')
    }
  }
}

const handleSelectionChange = (selection) => {
  selectedNews.value = selection.map(item => item.newsId)
}

const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/images/${imagePath}`
}

// 选择图片
const selectImage = () => {
  fileInput.value?.click();
}

// 处理图片选择
const handleImageSelect = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件');
      return;
    }

    // 验证文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片文件大小不能超过5MB');
      return;
    }

    // 获取文件名并存储
    formData.newsImagePath = file.name;

    ElMessage.success(`已选择图片: ${file.name}`);
  }

  // 清空文件输入框，允许重复选择同一文件
  event.target.value = '';
}

const exportToExcel = async () => {
  try {
    if (newsList.value.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    await NewsService.exportExcel(newsList.value)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 分页事件处理
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadNewsList();
}

// 审核相关方法
const getReviewStatusText = (status) => {
  switch (status) {
    case 0:
      return '未审核';
    case 1:
      return '已通过';
    case 2:
      return '已拒绝';
    default:
      return '未知';
  }
}

const getReviewStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning';
    case 1:
      return 'success';
    case 2:
      return 'danger';
    default:
      return 'info';
  }
}

// 审核新闻
const reviewNews = async (newsId, status) => {
  const statusText = status === 1 ? '通过' : '拒绝';

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}这个新闻吗？`,
      '确认审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    loading.value = true;
    const response = await NewsService.reviewNews(newsId, status);

    if (response.code === 200) {
      ElMessage.success(response.message || `审核${statusText}成功`);
      loadNewsList();
    } else {
      ElMessage.error(response.message || `审核${statusText}失败`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核新闻失败:', error);
      ElMessage.error('审核新闻失败，请检查网络连接');
    }
  } finally {
    loading.value = false;
  }
}

// 处理审核下拉菜单命令
const handleReviewCommand = (command) => {
  const { action, newsId } = command;
  const status = action === 'approve' ? 1 : 2;
  reviewNews(newsId, status);
}

// 生命周期
onMounted(() => {
  UserService.loadCurrentUser();
  loadNewsList()

})
</script>

<style scoped>
.news-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.page-header h2 {
  color: #333;
  margin: 0;
}

.search-section {
  margin-bottom: 20px;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.news-detail {
  padding: 20px 0;
}

.news-content {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  line-height: 1.6;
  max-height: 300px;
  overflow-y: auto;
}

.news-content img {
  max-width: 100%;
  height: auto;
}

.news-content p {
  margin: 0 0 10px 0;
}

.news-content h1,
.news-content h2,
.news-content h3,
.news-content h4,
.news-content h5,
.news-content h6 {
  margin: 15px 0 10px 0;
  font-weight: bold;
}

.news-content ul,
.news-content ol {
  margin: 10px 0;
  padding-left: 20px;
}

.news-content li {
  margin: 5px 0;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 40px;
  background: #f5f7fa;
  color: #909399;
  font-size: 12px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: nowrap;
}

.operation-buttons .el-button {
  margin: 0;
  flex-shrink: 0;
}

.image-upload-container {
  display: flex;
  align-items: center;
}

.image-input {
  flex: 1;
}

.select-image-btn {
  margin-left: 10px;
}

.image-preview {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.image-preview img {
  max-width: 100px;
  height: auto;
  margin-right: 10px;
}

.image-name {
  font-size: 12px;
  color: #999;
}

.editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
}

.editor-container .w-e-toolbar {
  border-top: none;
  border-left: none;
  border-right: none;
}

.editor-container .w-e-text-container {
  border: none;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

@media (max-width: 768px) {
  .action-section {
    flex-direction: column;
  }
}
</style>